package com.newasia.management.services;/**
 * Created by mic on 2019/7/30.
 */


import com.alibaba.fastjson.JSON;
import com.newasia.commons.tool.exception.ValidateException;
import com.newasia.management.IHomepageService;
import com.newasia.management.constants.ManagementRetCode;
import com.newasia.management.converter.HomePageConverter;
import com.newasia.management.dal.homepage.entitys.Panel;
import com.newasia.management.dal.homepage.entitys.PanelContent;
import com.newasia.management.dal.homepage.entitys.PanelContentExample;
import com.newasia.management.dal.homepage.entitys.PanelExample;
import com.newasia.management.dal.homepage.persistence.PanelContentMapper;
import com.newasia.management.dal.homepage.persistence.PanelMapper;
import com.newasia.management.dal.item.entitys.ItemSku;
import com.newasia.management.dal.item.entitys.ItemSkuExample;
import com.newasia.management.dal.item.entitys.ItemSpu;
import com.newasia.management.dal.item.persistence.ItemSkuMapper;
import com.newasia.management.dal.item.persistence.ItemSpuMapper;
import com.newasia.management.dal.user.entitys.SysMenu;
import com.newasia.management.dal.user.entitys.SysMenuExample;
import com.newasia.management.dal.user.persistence.SysMenuMapper;
import com.newasia.management.dto.HomepageBanner.*;
import com.newasia.management.dto.HomepageItem.*;
import com.newasia.management.dto.HomepageProduct.*;
import com.newasia.management.dto.HomepageProductGroup.*;
import com.newasia.management.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Slf4j
@Service
public class HomepageImpl implements IHomepageService {

    @Autowired
    PanelMapper panelMapper;

    @Autowired
    PanelContentMapper panelContentMapper;

    @Autowired
    HomePageConverter homePageConverter;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    SysMenuMapper sysMenuMapper;

    @Autowired
    ItemSkuMapper itemSkuMapper;

    @Autowired
    ItemSpuMapper itemSpuMapper;


    /**
     * 添加轮播图
     *
     * @return
     */
    @Override
    public CreateBannerResponse createBanner(CreateBannerRequest request) {
        CreateBannerResponse response = new CreateBannerResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try {
            clearHomepageCache();
            PanelContentExample example = new PanelContentExample();
            example.createCriteria().andPanelIdEqualTo((long) 7);
            long count = panelContentMapper.countByExample(example);
            if (count > 5) {
                throw new ValidateException(
                        ManagementRetCode.LIMIT_FIVE.getCode(),
                        ManagementRetCode.LIMIT_FIVE.getMessage()
                );
            }
            PanelContent data = new PanelContent();
            data.setPanelId((long) 7);
            data.setType(request.getType());
            data.setFullUrl(request.getFullUrl());
            data.setPicUrl(request.getPicUrl());
            data.setSortOrder(request.getSortOrder() == null ? 0 : request.getSortOrder());
            Date date = new Date();
            data.setCreated(date);
            panelContentMapper.insert(data);

        } catch (Exception e) {
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
            e.printStackTrace();
            return response;
        }
        return response;
    }


    /**
     * 删除轮播图
     *
     * @return
     */
    @Override
    public DeleteBannerResponse deleteBanner(Long bannerId) {
        DeleteBannerResponse response = new DeleteBannerResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try {
            clearHomepageCache();
            PanelContent panelContent = panelContentMapper.selectByPrimaryKey(bannerId);
            if (panelContent!=null&&panelContent.getPanelId().longValue() == 7) {
                panelContentMapper.deleteByPrimaryKey(bannerId);
            } else {
                throw new ValidateException(
                        ManagementRetCode.NOT_EXIST.getCode(),
                        ManagementRetCode.NOT_EXIST.getMessage()
                );
            }
        } catch (Exception e) {
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
            e.printStackTrace();
            return response;
        }
        return response;
    }


    /**
     * 修改轮播图
     *
     * @return
     */
    @Override
    public ChangeBannerResponse changeBanner(Long bannerId, ChangeBannerRequest request) {
        ChangeBannerResponse response = new ChangeBannerResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try {
            clearHomepageCache();
            PanelContent panelContent = panelContentMapper.selectByPrimaryKey(bannerId);

            if (panelContent.getPanelId().longValue() == 7) {
                request.setId(bannerId);
                request.setPanelId((long) 7);

                panelContentMapper.updateByPrimaryKeySelective(homePageConverter.request2banner(request));
            } else {
                throw new ValidateException(
                        ManagementRetCode.NOT_EXIST.getCode(),
                        ManagementRetCode.NOT_EXIST.getMessage()
                );
            }


        } catch (Exception e) {
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
            e.printStackTrace();
            return response;
        }
        return response;
    }


    /**
     * 获取轮播图列表
     *
     * @return
     */
    @Override
    public GetBannerResponse getBannerList() {
        GetBannerResponse response = new GetBannerResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try {
            PanelContentExample example = new PanelContentExample();
            PanelContentExample.Criteria criteria = example.createCriteria();
            criteria.andPanelIdEqualTo((long) 7);
            example.setOrderByClause("sort_order asc");
            List<PanelContent> panelContents = panelContentMapper.selectByExample(example);
            response.setData(homePageConverter.item2dto(panelContents));
        } catch (Exception e) {
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
            e.printStackTrace();
            return response;
        }
        return response;
    }
//-----------------------------------------------------------------------------------------------

    /**
     * 主页活动-增
     */
    @Override
    public CreateHomeItemResponse createHomeItem(CreateHomeItemRequest request) {
        CreateHomeItemResponse response = new CreateHomeItemResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try {
            clearHomepageCache();

            PanelContentExample example = new PanelContentExample();
            example.createCriteria().andPanelIdEqualTo((long) 8);
            long count = panelContentMapper.countByExample(example);
            if (count > 4) {
                throw new ValidateException(
                        ManagementRetCode.LIMIT_FOUR.getCode(),
                        ManagementRetCode.LIMIT_FOUR.getMessage()
                );
            }

            PanelContent data = new PanelContent();
            data.setPanelId((long) 8);
            data.setType(request.getType());
            data.setFullUrl(request.getFullUrl());
            data.setPicUrl(request.getPicUrl());
            data.setSortOrder(request.getSortOrder() == null ? 0 : request.getSortOrder());
            Date date = new Date();
            data.setCreated(date);
            panelContentMapper.insert(data);

        } catch (Exception e) {
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
            e.printStackTrace();
            return response;
        }
        return response;
    }

    @Override
    public DeleteHomeItemResponse deleteHomeItem(Long homeItemId) {
        DeleteHomeItemResponse response = new DeleteHomeItemResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try {
            clearHomepageCache();
            PanelContent panelContent = panelContentMapper.selectByPrimaryKey(homeItemId);
            if (panelContent!=null&&panelContent.getPanelId().longValue() == 8) {
                panelContentMapper.deleteByPrimaryKey(homeItemId);
            } else {
                throw new ValidateException(
                        ManagementRetCode.NOT_EXIST.getCode(),
                        ManagementRetCode.NOT_EXIST.getMessage()
                );
            }
        } catch (Exception e) {
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
            e.printStackTrace();
            return response;
        }
        return response;
    }

    @Override
    public ChangeHomeItemResponse changeHomeItem(Long homeItemId, ChangeBannerRequest request) {
        ChangeHomeItemResponse response = new ChangeHomeItemResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try {
            clearHomepageCache();
            PanelContent panelContent = panelContentMapper.selectByPrimaryKey(homeItemId);

            if (panelContent.getPanelId().longValue() == 8) {
                request.setId(homeItemId);
                request.setPanelId((long) 8);

                panelContentMapper.updateByPrimaryKeySelective(homePageConverter.request2banner(request));
            } else {
                throw new ValidateException(
                        ManagementRetCode.NOT_EXIST.getCode(),
                        ManagementRetCode.NOT_EXIST.getMessage()
                );
            }


        } catch (Exception e) {
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
            e.printStackTrace();
            return response;
        }
        return response;
    }



    @Override
    public GetHomeItemResponse getHomeItemList() {
        GetHomeItemResponse response = new GetHomeItemResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try {
            PanelContentExample example = new PanelContentExample();
            PanelContentExample.Criteria criteria = example.createCriteria();
            criteria.andPanelIdEqualTo((long) 8);

            example.setOrderByClause("sort_order asc");
            List<PanelContent> panelContents = panelContentMapper.selectByExample(example);
            response.setData(homePageConverter.item2dto(panelContents));
        } catch (Exception e) {
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
            e.printStackTrace();
            return response;
        }
        return response;
    }


    //--------------------------------------------------------------------------------
    /**
     * 主页商品组-增
     */
    @Override
    public CreateHomeProductGroupResponse createHomeProductGroup(CreateHomeProductGroupRequest request) {
        CreateHomeProductGroupResponse response = new CreateHomeProductGroupResponse();

        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try {
            clearHomepageCache();
            Panel data=new Panel();
            data.setName(request.getName());
            data.setSortOrder(request.getSortOrder()!=null?request.getSortOrder():10);
            data.setStatus(request.getStatus()!=null?request.getStatus():1);
            Date date = new Date();
            data.setCreated(date);
            panelMapper.insertSelective(data);

        } catch (Exception e) {
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
            e.printStackTrace();
            return response;
        }
        return response;
    }

    @Override
    public DeleteHomeProductGroupResponse deleteHomeProductGroup(Long homeProductGroupId) {
        DeleteHomeProductGroupResponse response = new DeleteHomeProductGroupResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try {
            clearHomepageCache();
            if(homeProductGroupId.longValue()==7||homeProductGroupId.longValue()==8){
                throw new ValidateException(
                        ManagementRetCode.CANT_DELETE.getCode(),
                        ManagementRetCode.CANT_DELETE.getMessage()
                );
            }

            PanelContentExample ex=new PanelContentExample();
            ex.createCriteria().andPanelIdEqualTo(homeProductGroupId);
            List<PanelContent> panelContents = panelContentMapper.selectByExample(ex);
            if(panelContents.size()>0){
                for(PanelContent item:panelContents){
                    panelContentMapper.deleteByPrimaryKey(item.getId());
                }
            }
            panelMapper.deleteByPrimaryKey(homeProductGroupId);
        } catch (Exception e) {
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
            e.printStackTrace();
            return response;
        }
        return response;
    }

    @Override
    public ChangeHomeProductGroupResponse changeHomeProductGroup(Long homeProductGroupId, ChangeHomeProductGroupRequest request) {
        ChangeHomeProductGroupResponse response = new ChangeHomeProductGroupResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try {
            clearHomepageCache();

            Panel data=new Panel();
            data.setId(homeProductGroupId);
            data.setName(request.getName());
            data.setSortOrder(request.getSortOrder());
            data.setStatus(request.getStatus());
            Date date = new Date();
            data.setUpdated(date);
            panelMapper.updateByPrimaryKeySelective(data);

        } catch (Exception e) {
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
            e.printStackTrace();
            return response;
        }
        return response;
    }

    @Override
    public GetHomeProductGroupResponse getHomeProductGroupList() {
        GetHomeProductGroupResponse response = new GetHomeProductGroupResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try {
//            clearHomepageCache();
            List<ProductGroupDto> data=new ArrayList<>();
            PanelExample ex=new PanelExample();
            ex.createCriteria().andIdNotEqualTo((long) 7).andIdNotEqualTo((long) 8);
            ex.setOrderByClause("sort_order asc,id asc");
            List<Panel> panels = panelMapper.selectByExample(ex);
            if(panels.size()>0){
                for (Panel item:panels) {
                    ProductGroupDto productGroupDto = new ProductGroupDto();
                    productGroupDto.setId(item.getId());
                    productGroupDto.setName(item.getName());
                    productGroupDto.setSortOrder(item.getSortOrder());
                    productGroupDto.setStatus(item.getStatus());



                    PanelContentExample ee=new PanelContentExample();
                    ee.createCriteria().andPanelIdEqualTo(item.getId());
                    List<PanelContent> panelContents = panelContentMapper.selectByExample(ee);
//                    List<Long> list=new ArrayList<>();
                    List<HomeProductDto> children=new ArrayList<>();
                    for (PanelContent p:panelContents) {
                        HomeProductDto dto=new HomeProductDto();
                        dto.setId(p.getId());
                        dto.setSkuId(p.getSkuId());
                        dto.setTitle(p.getPicUrl());
                        dto.setSellPoint(p.getPicUrl2());
                        dto.setCover(p.getFullUrl());
                        children.add(dto);
                    }


//
//                    if(list.size()>0){
//                        ItemSkuExample eee=new ItemSkuExample();
//                        eee.createCriteria().andSkuIdIn(list);
//                        List<ItemSku> itemSkus = itemSkuMapper.selectByExampleWithBLOBs(eee);
//                        for (ItemSku sku:itemSkus) {
//                            HomeProductDto dto=new HomeProductDto();
//
//                            ItemSpu itemSpu = itemSpuMapper.selectByPrimaryKey(sku.getSpuId());
//                            dto.setId();
//                            dto.setSkuId(sku.getSkuId());
//                            dto.setSellPoint(itemSpu.getSellPoint());
//                            dto.setTitle(itemSpu.getTitle());
//                            List<String> ii = JSON.parseArray(sku.getSkuImage(), String.class);
//                            if(ii.size()>0){
//                                dto.setCover(ii.get(0));
//                            }else{
//                                dto.setCover(itemSpu.getImage());
//                            }
//                            children.add(dto);
//                        }
//
//                    }

                    productGroupDto.setChildren(children);
                    data.add(productGroupDto);
                }
            }

            response.setData(data);
        } catch (Exception e) {
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
            e.printStackTrace();
            return response;
        }
        return response;
    }

    //--------------------------------------------------------------------------------
    /**
     * 主页商品-增
     */

    @Override
    public CreateHomeProductResponse createHomeProduct(CreateHomeProductRequest request) {

        CreateHomeProductResponse response = new CreateHomeProductResponse();

        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try {
            clearHomepageCache();
            PanelContent p=new PanelContent();
            if (request.getGroupId().longValue()!=7&&request.getGroupId().longValue()!=8){
                p.setPanelId(request.getGroupId());
                p.setSkuId(request.getSkuId());
                ItemSku sku = itemSkuMapper.selectByPrimaryKey(request.getSkuId());
                ItemSpu itemSpu = itemSpuMapper.selectByPrimaryKey(sku.getSpuId());
                List<String> ii = JSON.parseArray(sku.getSkuImage(), String.class);
                if(ii.size()>0){
                    p.setFullUrl(ii.get(0));
                }else{
                    p.setFullUrl(itemSpu.getImage());
                }
                Date date=new Date();
                p.setCreated(date);
                p.setPicUrl(itemSpu.getTitle());
                p.setPicUrl2(itemSpu.getSellPoint());
                p.setType(0);
                p.setSortOrder(request.getSortOrder()!=null?request.getSortOrder():10);
                panelContentMapper.insertSelective(p);
            }else{
                throw new ValidateException(
                        ManagementRetCode.CANT_DELETE.getCode(),
                        ManagementRetCode.CANT_DELETE.getMessage()
                );
            }


        } catch (Exception e) {
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
            e.printStackTrace();
            return response;
        }
        return response;

    }

    @Override
    public DeleteHomeProductResponse deleteHomeProduct(Long homeProductId) {

        DeleteHomeProductResponse response = new DeleteHomeProductResponse();

        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try {
            clearHomepageCache();
           panelContentMapper.deleteByPrimaryKey(homeProductId);

        } catch (Exception e) {
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
            e.printStackTrace();
            return response;
        }
        return response;
    }

    @Override
    public ChangeHomeProductResponse changeHomeProduct(Long homeProductId, ChangeHomeProductRequest request) {
        ChangeHomeProductResponse response = new ChangeHomeProductResponse();

        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try {
            clearHomepageCache();
            PanelContent p=new PanelContent();
            p.setId(homeProductId);

            ItemSku sku = itemSkuMapper.selectByPrimaryKey(request.getSkuId());
            ItemSpu itemSpu = itemSpuMapper.selectByPrimaryKey(sku.getSpuId());
            List<String> ii = JSON.parseArray(sku.getSkuImage(), String.class);
            if(ii.size()>0){
                p.setFullUrl(ii.get(0));
            }else{
                p.setFullUrl(itemSpu.getImage());
            }

            Date date=new Date();
            p.setSkuId(request.getSkuId());
            p.setUpdated(date);
            p.setPicUrl(itemSpu.getTitle());
            p.setPicUrl2(itemSpu.getSellPoint());
            p.setSortOrder(request.getSortOrder());

            panelContentMapper.updateByPrimaryKeySelective(p);

        } catch (Exception e) {
            log.error("ManagementItemCatServiceImpl.getItemCat occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
            e.printStackTrace();
            return response;
        }
        return response;
    }

    @Override
    public GetHomeProductResponse getHomeProductList() {
        return null;
    }


    private void clearHomepageCache() {
        SysMenuExample ex = new SysMenuExample();
        ex.createCriteria().andStatusEqualTo(0);
        List<SysMenu> sysMenus = sysMenuMapper.selectByExample(ex);
        StringBuilder s = new StringBuilder("home_page");
        s.append(":").append(0);
        RBucket rb = redissonClient.getBucket(s.toString());
        rb.expire(0, TimeUnit.DAYS);

        StringBuilder ss = new StringBuilder("home_page");
        ss.append(":").append(null + "");
        RBucket rb1 = redissonClient.getBucket(ss.toString());
        rb1.expire(0, TimeUnit.DAYS);


        for (SysMenu menu : sysMenus) {
            StringBuilder stringBuilder = new StringBuilder("home_page");
            stringBuilder.append(":").append(menu.getMenuId());
            RBucket rBucket = redissonClient.getBucket(stringBuilder.toString());
            rBucket.expire(0, TimeUnit.DAYS);
        }
    }
}
